package cn.com.cifi.mars.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.bo.PublicInformFetchBO;
import cn.com.cifi.mars.bean.bo.PublicSignPlanBO;
import cn.com.cifi.mars.bean.bo.SignIndicatorsBO;
import cn.com.cifi.mars.bean.bo.SignProductCodeBO;
import cn.com.cifi.mars.bean.bo.SignSupplyDetailBO;
import cn.com.cifi.mars.bean.bo.StageDetailsBO;
import cn.com.cifi.mars.bean.dto.OrgDTO;
import cn.com.cifi.mars.bean.dto.ProductSupplyDetail;
import cn.com.cifi.mars.bean.dto.SignDetailProductDto;
import cn.com.cifi.mars.bean.dto.SignPlanDetailDto;
import cn.com.cifi.mars.bean.dto.SignPlanDto;
import cn.com.cifi.mars.bean.param.esb.EsbInfoReq;
import cn.com.cifi.mars.bean.param.esb.EsbInformReqParam;
import cn.com.cifi.mars.bean.param.esb.EsbReqParam;
import cn.com.cifi.mars.bean.vo.signPlan.ProductSignPlanVo;
import cn.com.cifi.mars.bean.vo.signPlan.req.ProductSignPlanParam;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.constant.ModifySourceTypeEunm;
import cn.com.cifi.mars.constant.ModuleTypeEunm;
import cn.com.cifi.mars.constant.SalyTypeEnum;
import cn.com.cifi.mars.constant.StageStatusEnum;
import cn.com.cifi.mars.constant.VersionAttrEnum;
import cn.com.cifi.mars.constant.VersionCreateEnum;
import cn.com.cifi.mars.constant.VersionEventEnum;
import cn.com.cifi.mars.constant.VersionStatusEnum;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.constant.WhetherEnum;
import cn.com.cifi.mars.entity.BudgetVersionIdentify;
import cn.com.cifi.mars.entity.EsbPushLog;
import cn.com.cifi.mars.entity.MdmProject;
import cn.com.cifi.mars.entity.MdmStage;
import cn.com.cifi.mars.entity.PriceVersion;
import cn.com.cifi.mars.entity.ReturnPlanVersion;
import cn.com.cifi.mars.entity.SignPlanVersion;
import cn.com.cifi.mars.entity.SignPlanVersionDetail;
import cn.com.cifi.mars.entity.SignPlanVersionSupplyDetail;
import cn.com.cifi.mars.entity.SupplyPlanVersion;
import cn.com.cifi.mars.entity.VersionLog;
import cn.com.cifi.mars.entity.common.IdmUser;
import cn.com.cifi.mars.mapper.mars.BudgetVersionIdentifyMapper;
import cn.com.cifi.mars.mapper.mars.PriceVersionMapper;
import cn.com.cifi.mars.mapper.mars.ProjectMapper;
import cn.com.cifi.mars.mapper.mars.SignPlanVersionDetailMapper;
import cn.com.cifi.mars.mapper.mars.SignPlanVersionMapper;
import cn.com.cifi.mars.mapper.mars.SignPlanVersionSupplyDetailMapper;
import cn.com.cifi.mars.mapper.mars.StageMapper;
import cn.com.cifi.mars.mapper.mars.SupplyPlanVersionDetailMapper;
import cn.com.cifi.mars.mapper.mars.SupplyPlanVersionMapper;
import cn.com.cifi.mars.mapper.mars.VersionLogMapper;
import cn.com.cifi.mars.service.BudgetLockRecordService;
import cn.com.cifi.mars.service.EsbPushLogService;
import cn.com.cifi.mars.service.SignPlanVersionDetailService;
import cn.com.cifi.mars.service.SignPlanVersionService;
import cn.com.cifi.mars.service.VersionLogService;
import cn.com.cifi.mars.util.BasicAuthClient;
import cn.com.cifi.mars.util.BigDecimalUtils;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.NumberUtils;
import cn.com.cifi.mars.util.StrUtils;
import cn.com.cifi.mars.util.UUIDUtils;
import cn.com.cifi.mars.util.VersionUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 签约计划版本明细表 服务实现类
 * </p
 *
 * @author yyd
 * @since 2019-11-08
 */
@Slf4j
@Service
public class SignPlanVersionDetailServiceImpl extends ServiceImpl<SignPlanVersionDetailMapper, SignPlanVersionDetail> implements SignPlanVersionDetailService {

    @Autowired
    private SignPlanVersionMapper signPlanVersionMapper;
    @Autowired
    private SignPlanVersionDetailMapper signPlanVersionDetailMapper;
    @Autowired
    private SignPlanVersionSupplyDetailMapper signPlanVersionSupplyDetailMapper;
    @Autowired
    private PriceVersionMapper priceVersionMapper;
    @Autowired
	private SignPlanVersionService signPlanVersionService;
    @Autowired
    private EsbPushLogService esbPushLogService;
    @Autowired
    private VersionLogMapper versionLogMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private SupplyPlanVersionMapper supplyPlanVersionMapper;
    @Autowired
    private SupplyPlanVersionDetailMapper supplyPlanVersionDetailMapper;
    @Autowired
    private StageMapper stageMapper;
    @Autowired
	private BudgetLockRecordService budgetLockRecordService;
    @Autowired
    BudgetVersionIdentifyMapper budgetVersionIdentifyMapper;
    @Autowired
	private VersionLogService versionLogService;
    
    @Autowired
	private SignPlanVersionDetailService signPlanVersionDetailService;
    
    
    
    @Value("${sign_push_url}")
    private String signPushUrl;
    
    @Value("${inform_fetch_url}")
    private String informFetchUrl;
    
    @Value("${api_name}")
	private String api_name;
	
	@Value("${api_key}")
	private String api_key;

    /**
     * 查询产品构成的签约计划
     */
    @Override
    public ProductSignPlanVo getProductSignPlan(ProductSignPlanParam productSignPlanParam) {
        String versionId = productSignPlanParam.getVersionId();
        SignPlanVersion spv = signPlanVersionMapper.selectByIdAndDel(versionId,IsDeleteEnum.NO.getKey());
        if (spv == null) {
            throw new MsgException(CodeEnum.NOT_SIGN_PLAN_VERSION);
        }
        //版本类型
        String versionType = spv.getVersionType();
//        //若版本是预算版,则取预算版基于的签约计划版本
//        if(versionType.equals(VersionTypeEunm.BUDGET.getKey())){
//            SignPlanVersion sourceSign = signPlanVersionMapper.selectByIdAndDel(spv.getSourceSignId(),IsDeleteEnum.NO.getKey());
//            versionType = sourceSign.getVersionType();
//        }


        SignProductCodeBO signSupplyBO=new SignProductCodeBO();
        signSupplyBO.setVersionId(productSignPlanParam.getVersionId());
        signSupplyBO.setPid(productSignPlanParam.getPid());
        signSupplyBO.setProductCode(productSignPlanParam.getProductCode());
        signSupplyBO.setBusinessType(productSignPlanParam.getBusinessType());
        signSupplyBO.setFreeType(productSignPlanParam.getFreeType());
        signSupplyBO.setProType(productSignPlanParam.getProType());
        signSupplyBO.setIsDel(IsDeleteEnum.NO.getKey());

        SignProductCodeBO signDetailBO=new SignProductCodeBO();
        signDetailBO.setVersionId(productSignPlanParam.getVersionId());
        signDetailBO.setPid(productSignPlanParam.getGroupId());
        signDetailBO.setProductCode(productSignPlanParam.getProductCode());
        signDetailBO.setBusinessType(productSignPlanParam.getBusinessType());
        signDetailBO.setFreeType(productSignPlanParam.getFreeType());
        signDetailBO.setProType(productSignPlanParam.getProType());
        signDetailBO.setIsDel(IsDeleteEnum.NO.getKey());

        ProductSignPlanVo vo=new ProductSignPlanVo();
        List<ProductSupplyDetail> productSupplyDetailList=new ArrayList<>();
        //产品构成供货计划详情列表 productSupplyDetailList;

        List<SignPlanVersionSupplyDetail> spvsdList=signPlanVersionSupplyDetailMapper.selectSignPlanSupplyDetail(signSupplyBO);
        //供货详情列表装换（有实际供货取实际供货，无实际供货取计划供货）
        List<SignSupplyDetailBO> ssdBOList= signPlanVersionService.switchSignSupplyDetailBO(spvsdList);
        //供货批次
        int supplySize = ssdBOList.size();
        //供货计划批次
        int supplyPlanSize = ssdBOList.stream().filter(s -> { return s.getIsActual() == 0; }).collect(Collectors.toList()).size();
        //供货实际批次
        int supplyActualSize = ssdBOList.stream().filter(s -> { return s.getIsActual() == 1; }).collect(Collectors.toList()).size();
        vo.setSupplySize(supplySize);
        vo.setSupplyPlanSize(supplyPlanSize);
        vo.setSupplyActualSize(supplyActualSize);

        //将相同一天的数据合并
        Map<String,SignSupplyDetailBO> supplyDetailMap=new HashMap<>();
        for (SignSupplyDetailBO ssdBO:ssdBOList){
            String time = LocalDateTimeUtils.formatTime(ssdBO.getSupplyDate(),"yyyy-MM-dd");
            if(supplyDetailMap.containsKey(time)){
                SignSupplyDetailBO supplyDetail = supplyDetailMap.get(time);
                //是否车位楼栋
                if(ssdBO.getIsParking().equals(WhetherEnum.NO.getKey())){
                    //房源套数
                    supplyDetail.setRoomNum(supplyDetail.getRoomNum()+ssdBO.getRoomNum());
                    //面积
                    supplyDetail.setSaleArea(supplyDetail.getSaleArea().add(ssdBO.getSaleArea()));
                    //金额
                    supplyDetail.setHouseCommodityValue(supplyDetail.getHouseCommodityValue().add(ssdBO.getHouseCommodityValue()));
                    //均价
                    supplyDetail.setAveragePriceHouse(BigDecimalUtils.divBigDecimal(supplyDetail.getHouseCommodityValue(),supplyDetail.getSaleArea(),4));
                }else {
                    //车位数
                    supplyDetail.setParkingNum(supplyDetail.getParkingNum()+ssdBO.getParkingNum());
                    //金额
                    supplyDetail.setNotCommodityValue(supplyDetail.getNotCommodityValue().add(ssdBO.getNotCommodityValue()));
                    //均价
                    supplyDetail.setAveragePriceParking(BigDecimalUtils.divInteger(supplyDetail.getNotCommodityValue(),supplyDetail.getParkingNum(),4));
                }
                supplyDetailMap.put(time,supplyDetail);
            }else {
                supplyDetailMap.put(time,ssdBO);
            }
        }
        ArrayList<SignSupplyDetailBO> signSupplyDetailBOS = new ArrayList<>(supplyDetailMap.values());

        for (SignSupplyDetailBO ssdBO:signSupplyDetailBOS){
            ProductSupplyDetail productSupplyDetail=new ProductSupplyDetail();
            productSupplyDetail.setId(ssdBO.getId());
            //供货日期
            productSupplyDetail.setSupplyDate(ssdBO.getSupplyDate());
            //是否车位楼栋
            if(ssdBO.getIsParking().equals(WhetherEnum.NO.getKey())){
                //房源套数
                productSupplyDetail.setNum(ssdBO.getRoomNum().toString());
                //面积
                productSupplyDetail.setSaleArea(ssdBO.getSaleArea().toString());
                //金额
                productSupplyDetail.setPrice(ssdBO.getHouseCommodityValue().toString());
                //均价
                productSupplyDetail.setAvgPrice(ssdBO.getAveragePriceHouse().toString());
                //套均面积
                if(ssdBO.getRoomNum()!=0){
                    productSupplyDetail.setAvgRoomArea(BigDecimalUtils.divInteger(ssdBO.getSaleArea(),ssdBO.getRoomNum(),4).toString());
                }
            }else {
                //车位数
                productSupplyDetail.setNum(ssdBO.getParkingNum().toString());
                //金额
                productSupplyDetail.setPrice(ssdBO.getNotCommodityValue().toString());
                //均价
                productSupplyDetail.setAvgPrice(ssdBO.getAveragePriceParking().toString());
            }
            productSupplyDetailList.add(productSupplyDetail);
        }
        //排序
        productSupplyDetailList=productSupplyDetailList
                .stream()
                .sorted(Comparator.comparing(ProductSupplyDetail::getSupplyDate))
                .collect(Collectors.toList());

        //月度签约计划 signPlanDetailDtoList;
        List<SignPlanDetailDto> signPlanDetailDtoList = signPlanVersionDetailMapper.selectSignPlanDetail(signDetailBO);
        SignDetailProductDto signDetailProductDto=null;


        if(CollectionUtils.isNotEmpty(signPlanDetailDtoList)){
            signDetailProductDto=new SignDetailProductDto();
            String signDetailId=signPlanDetailDtoList.get(0).getId();
            SignPlanVersionDetail spvd = signPlanVersionDetailMapper.selectById(signDetailId);
            signDetailProductDto.setVersionId(spvd.getVersionId());
            signDetailProductDto.setGroupId(spvd.getGroupId());
            signDetailProductDto.setGroupName(spvd.getGroupName());
            signDetailProductDto.setProductCode(spvd.getProductCode());
            signDetailProductDto.setProductName(spvd.getProductName());
            signDetailProductDto.setBusinessType(spvd.getBusinessType());
            signDetailProductDto.setBusinessTypeName(spvd.getBusinessTypeName());
            signDetailProductDto.setFreeType(spvd.getFreeType());
            signDetailProductDto.setFreeTypeName(spvd.getFreeTypeName());
            signDetailProductDto.setProType(spvd.getProType());
            signDetailProductDto.setProTypeName(spvd.getProTypeName());
        }

        vo.setVersionId(versionId);
        vo.setVersionType(versionType);
        vo.setAffiliationMonth(spv.getAffiliationMonth());
        vo.setSignDetailProductDto(signDetailProductDto);
        vo.setProductSupplyDetailList(productSupplyDetailList);
        vo.setSignPlanDetailDtoList(signPlanDetailDtoList);
        return vo;
    }
    
    /**
     * versionId 签约计划版本ID
     * type 推送类型（1-手动推送；2-自动推送）
     */
	@Override
	public void sendSignPlan(String versionId,int type) {
		EsbReqParam param = prepareEsbParam(versionId);
		log.info(JSON.toJSONString(param));
		BasicAuthClient bac = new BasicAuthClient();
		String result =  bac.post(signPushUrl, JSON.toJSONString(param),api_name,api_key);
		log.info("##### 推送签约计划接口 参数："+ JSON.toJSONString(param));
		log.info("##### 推送签约计划接口 数据："+ result);
		if(StrUtils.isNotEmpty(result)) {
			JSONObject object = (JSONObject) JSONObject.parse(result);
			JSONObject esbInfoObj = object.getJSONObject("esbInfo");
			String returnStatus = esbInfoObj.getString("returnStatus");
			//成功
			if(returnStatus.equals("S")) {
				EsbPushLog log = esbPushLogService.getByVersionId(versionId);
				SignPlanVersion signPlanVersion = signPlanVersionMapper.selectById(versionId);
				if(log == null) {
					log = new EsbPushLog();
					log.setId(UUIDUtils.create());
					log.setVersionId(versionId);
					log.setStageId(signPlanVersion.getProjectfId());
					log.setUrl(signPushUrl);
					log.setSys("营销费控");
					log.setPushContent(JSON.toJSONString(param));
					log.setReturnContent(result);
					log.setCreateTime(LocalDateTime.now());
					log.setIsSuccess(IsDeleteEnum.NO.getKey());
					log.setFailTime(IsDeleteEnum.NO.getKey());
					log.setType(type);
					esbPushLogService.insert(log);
				}else {
					if(log.getIsSuccess().intValue() == IsDeleteEnum.NO.getKey()) {
						log.setCreateTime(LocalDateTime.now());
					}else {
						log.setCreateTime(LocalDateTime.now());
						log.setIsSuccess(IsDeleteEnum.NO.getKey());
					}
					log.setType(type);
					esbPushLogService.update(log);
				}
			}else {
				EsbPushLog log = esbPushLogService.getByVersionId(versionId);
				SignPlanVersion signPlanVersion = signPlanVersionMapper.selectById(versionId);
				if(log == null) {
					log = new EsbPushLog();
					log.setId(UUIDUtils.create());
					log.setVersionId(versionId);
					log.setStageId(signPlanVersion.getProjectfId());
					log.setUrl(signPushUrl);
					log.setSys("营销费控");
					log.setPushContent(JSON.toJSONString(param));
					log.setReturnContent(result);
					log.setCreateTime(LocalDateTime.now());
					log.setIsSuccess(IsDeleteEnum.NO.getKey());
					log.setFailTime(IsDeleteEnum.YES.getKey());
					log.setType(type);
					esbPushLogService.insert(log);
				}else {
					log.setCreateTime(LocalDateTime.now());
					log.setIsSuccess(IsDeleteEnum.YES.getKey());
					log.setFailTime(log.getFailTime().intValue() + 1);
					log.setType(type);
					esbPushLogService.update(log);
				}
			}
		}
	}

	private EsbReqParam prepareEsbParam(String versionId) {
		EsbReqParam param = new EsbReqParam();
		PublicSignPlanBO bo = getSignPlanVersionDetail(versionId);
		EsbInfoReq esbInfo = new EsbInfoReq();
		esbInfo.setAttr1("null");
		esbInfo.setAttr2("null");
		esbInfo.setAttr3("null");
		esbInfo.setInstId("");
		esbInfo.setRequestTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
		param.setEsbInfo(esbInfo);
		param.setRequestInfo(bo);
		return param;
	}


	@Override
	public void sendSignPlanBatch(String regionId, String projectId, String versionType) {
		List<SignPlanDto> list = signPlanVersionMapper.selectListByVersionType(versionType,IsDeleteEnum.NO.getKey(),StageStatusEnum.CTIVE.getKey());
		List<SignPlanDto> dataList = new ArrayList<>(); 
		if(CollectionUtils.isNotEmpty(list)) {
			if(StrUtils.isNotEmpty(regionId)) {
				dataList = list.stream().filter(x-> x.getRegionId().equals(regionId)).collect(Collectors.toList()); 
			}
			if(StrUtils.isNotEmpty(projectId)) {
				dataList = list.stream().filter(x-> x.getProjectId().equals(projectId)).collect(Collectors.toList());
			}
			if(StrUtils.isEmpty(regionId) && StrUtils.isEmpty(projectId)) {
				dataList.addAll(list);
			}
			
			dataList.stream().forEach(x->{
				String versionId = x.getVersionId();
				sendSignPlan(versionId,1);
			});
			
		}
	}

	@Override
	public PublicSignPlanBO getSignPlanVersionDetail(String versionId) {
		PublicSignPlanBO bo = new PublicSignPlanBO();
		SignIndicatorsBO signIndicators = new SignIndicatorsBO();
		List<StageDetailsBO> stageDetails = new ArrayList<>();
		SignPlanVersion signPlanVersion = signPlanVersionMapper.selectByIdAndDel(versionId, IsDeleteEnum.NO.getKey());
		if(signPlanVersion != null) {
			PriceVersion priceVersion = priceVersionMapper.selectByVersionId(signPlanVersion.getSourcePriceId(), IsDeleteEnum.NO.getKey());
			String projectId = signPlanVersion.getProjectId();
			LocalDateTime affiliationMonth = LocalDateTimeUtils.toLocalDateTime(signPlanVersion.getAffiliationMonth());
			OrgDTO org = signPlanVersionDetailMapper.selectProjectOrg(projectId);
			signIndicators.setSycnId("GXC");
			signIndicators.setSignPlanName(VersionTypeEunm.getValueByKey(signPlanVersion.getVersionType()));
			signIndicators.setSignPlanVersion(signPlanVersion.getVersionNum());
			signIndicators.setProjectId(projectId);
			if(org != null) {
				signIndicators.setDivisionId(org.getRegionId());
				signIndicators.setDivisionName(org.getRegionName());
				signIndicators.setProjectName(org.getProjectName());
			}
			signIndicators.setYear(getYear(signPlanVersion));
			
			BudgetVersionIdentify obj = budgetVersionIdentifyMapper.selectVersion(IsDeleteEnum.NO.getKey());
			
			//详情
			List<SignPlanVersionDetail> signPlanVersionDetailList = signPlanVersionDetailMapper.selectByVersionId(versionId,IsDeleteEnum.NO.getKey());
			Set<String> yearSet = getYears(signPlanVersionDetailList);
			for(String year : yearSet) {
				StageDetailsBO stageDetailsBO = new StageDetailsBO();
				stageDetailsBO.setStageId(signPlanVersion.getProjectfId());
				stageDetailsBO.setStageName(signPlanVersion.getStageName());
				stageDetailsBO.setBaseVersion(prepareBaseVersion(priceVersion == null ? "" : priceVersion.getVersionType()));
				stageDetailsBO.setVersionType(prepareBaseVersion(signPlanVersion.getVersionType()));
				stageDetailsBO.setBudgetTarget(null);
				stageDetailsBO.setBudgetMatch(null);
				if(obj != null && StrUtils.isNotEmpty(obj.getIsBudget()) && obj.getIsBudget().equals("是")) {
					stageDetailsBO.setBudgetIdentifyCode(obj.getVersionCode());
					stageDetailsBO.setBudgetIdentifyName(obj.getVersionIdentify());
				}else {
					stageDetailsBO.setBudgetIdentifyCode(null);
					stageDetailsBO.setBudgetIdentifyName(null);
				}
				stageDetailsBO.setYear(year);
				stageDetailsBO.setJanuaryIndicators(getYearMonthSignPlan(year+"-01",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setFebruaryIndicators(getYearMonthSignPlan(year+"-02",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setMarchIndicators(getYearMonthSignPlan(year+"-03",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setAprilIndicators(getYearMonthSignPlan(year+"-04",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setMayIndicators(getYearMonthSignPlan(year+"-05",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setJuneIndicators(getYearMonthSignPlan(year+"-06",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setJulyIndicators(getYearMonthSignPlan(year+"-07",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setAugustIndicators(getYearMonthSignPlan(year+"-08",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setSeptemberIndicators(getYearMonthSignPlan(year+"-09",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setOctoberIndicators(getYearMonthSignPlan(year+"-10",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setNovemberIndicators(getYearMonthSignPlan(year+"-11",affiliationMonth,signPlanVersionDetailList));
				stageDetailsBO.setDecemberIndicators(getYearMonthSignPlan(year+"-12",affiliationMonth,signPlanVersionDetailList));
			
				stageDetails.add(stageDetailsBO);
			}
			
			bo.setSignIndicators(signIndicators);
			bo.setStageDetails(stageDetails);
		}else {
			log.info("签约计划版本不存在");
		}
		
		return bo;
	}

	public String getYearMonthSignPlan(String yearMonth,LocalDateTime affiliationMonth,List<SignPlanVersionDetail> signPlanVersionDetailList) {
		int affiliationMonthInt = LocalDateTimeUtils.toIntYearMonth(affiliationMonth);
		BigDecimal earlySignSumPrice = BigDecimal.ZERO;
		BigDecimal supplySignSumPrice = BigDecimal.ZERO;
		
		if(CollectionUtils.isNotEmpty(signPlanVersionDetailList)) {
			for(SignPlanVersionDetail detail : signPlanVersionDetailList) {
				LocalDateTime signPlanTime = detail.getSignPlanTime();
				if(signPlanTime != null) {
					String month = LocalDateTimeUtils.formatTime(signPlanTime, "yyyy-MM");
					if(month.equals(yearMonth)) {
						int monthInt = LocalDateTimeUtils.toIntYearMonth(signPlanTime);
						if(monthInt < affiliationMonthInt) {//取实际
							earlySignSumPrice = NumberUtils.BigDecimalADD(5, earlySignSumPrice, detail.getEarlySignSumPriceActual());
							supplySignSumPrice = NumberUtils.BigDecimalADD(5, supplySignSumPrice, detail.getSupplySignSumPriceActual());
						}else {//取计划
							earlySignSumPrice = NumberUtils.BigDecimalADD(5, earlySignSumPrice, detail.getEarlySignSumPrice());
							supplySignSumPrice = NumberUtils.BigDecimalADD(5, supplySignSumPrice, detail.getSupplySignSumPrice());
						}
					}
				}
			}
		}
		return NumberUtils.BigDecimalADD(5, earlySignSumPrice, supplySignSumPrice).toString();
	}
	
	private Set<String> getYears(List<SignPlanVersionDetail> signPlanVersionDetailList) {
		Set<String> yearSet = new TreeSet<>(); 
		if(CollectionUtils.isNotEmpty(signPlanVersionDetailList)) {
			signPlanVersionDetailList.forEach(signPlanVersionDetail->{
					LocalDateTime signPlanTime = signPlanVersionDetail.getSignPlanTime();
					if(signPlanTime != null) {
						yearSet.add(signPlanTime.getYear()+"");
					}
			});
		}
		return yearSet;
	}
	
	private String prepareBaseVersion(String versionType) {
		String baseVersion = "";
		if(VersionTypeEunm.INVESTMENT.getKey().equals(versionType)) {
			baseVersion = "1";
		}else if(VersionTypeEunm.WARPLAN.getKey().equals(versionType)) {
			baseVersion = "2";
		}else if(VersionTypeEunm.BUDGET.getKey().equals(versionType)) {
			baseVersion = "3";
		}else if(VersionTypeEunm.DYNAMIC.getKey().equals(versionType)) {
			baseVersion = "4";
		}
		return baseVersion;
	}
	
	private String getYear(SignPlanVersion signPlanVersion) {
		String year = "";
		String versionType  = signPlanVersion.getVersionType();
		String affiliationMonth = signPlanVersion.getAffiliationMonth();
		if(VersionTypeEunm.BUDGET.getKey().equals(versionType)) {
			year = signPlanVersion.getCompileYear();
		}else {
			if(StrUtils.isNotEmpty(affiliationMonth)) {
				year = affiliationMonth.split("-")[0];
			}
		}
		return year;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void autoCopySignPlanVersion(String versionId) {
		SignPlanVersion signPlanVersion = signPlanVersionMapper.selectByIdAndDel(versionId, IsDeleteEnum.NO.getKey());
		String version = "";
		if(signPlanVersion != null) {
			version = signPlanVersion.getVersionIdentify();
			if(StrUtils.isNotEmpty(version)) {
				// 查询上一版签约计划
		        SignPlanVersion oldSignPlanVersion = signPlanVersionMapper.selectBudgetSignPlan(signPlanVersion.getProjectfId(), VersionTypeEunm.BUDGET.getKey(),
		        		version, VersionStatusEnum.SYSGENERATION.getKey(), IsDeleteEnum.NO.getKey());

		        SignPlanVersion newSignPlanVersion = new SignPlanVersion();
		        
		        BeanUtils.copyProperties(signPlanVersion, newSignPlanVersion);
		        // 新版本id
		        String signPlanVersionId = UUIDUtils.create();
		        newSignPlanVersion.setId(signPlanVersionId);
		        // 查询最新审批通过的签约版本
		        if (null == oldSignPlanVersion) {
		            newSignPlanVersion.setVersionNum(VersionUtils.bigVersionInc(null));
		        } else {
		            newSignPlanVersion.setVersionNum(VersionUtils.bigVersionInc(oldSignPlanVersion.getVersionNum()));
		        }
		        String affiliationMonth =signPlanVersion.getAffiliationMonth();
		        if(StrUtils.isEmpty(affiliationMonth)) {
		        	affiliationMonth = LocalDateTimeUtils.formatTime(signPlanVersion.getCreateTime(),"yyyy-MM");
		        }
		        newSignPlanVersion.setSourceSignId(versionId);
		        newSignPlanVersion.setVersionState(VersionStatusEnum.SUCCESSAPPROVED.getKey());
		        newSignPlanVersion.setVersionType(VersionTypeEunm.BUDGET.getKey());
		        newSignPlanVersion.setVersionCreate(VersionCreateEnum.AUTOMATICCOPY.getKey());
		        newSignPlanVersion.setVersionIdentify(version);
		        newSignPlanVersion.setAffiliationMonth(affiliationMonth);
		        newSignPlanVersion.setCompileYear(version.substring(0, 4));
		        newSignPlanVersion.setCreateBy(Constants.SYS);
		        newSignPlanVersion.setCreateTime(LocalDateTime.now());
		        newSignPlanVersion.setUpdateBy(null);
		        newSignPlanVersion.setUpdateTime(null);
		        newSignPlanVersion.setIsStageNewest(0);
		        
		        //预算版签约版本
		        signPlanVersionMapper.insert(newSignPlanVersion);
		        //签约版本详情
		        signPlanVersionDetailMapper.copyVesionDetail(versionId,signPlanVersionId);
		        //签约供货版本详情
		        signPlanVersionSupplyDetailMapper.copyVesionDetail(versionId,signPlanVersionId);
		        //复制供货计划
		        copySupplyPlanVersion(newSignPlanVersion);
		        
		        saveVersionLog(signPlanVersionId,VersionEventEnum.SYS_GENERATE.getKey(),"",signPlanVersion.getCreateBy(),"新建签约计划",null);
			
		        //推送Esb接口-费控系统
		        signPlanVersionDetailService.sendSignPlan(signPlanVersionId,2);
			
			}
		}
		
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void copyToBudgetVersion(String versionId,String versionIdentify,IdmUser user) {
		SignPlanVersion signPlanVersion = signPlanVersionMapper.selectByIdAndDel(versionId, IsDeleteEnum.NO.getKey());
		if(signPlanVersion != null) {
			//1、项目锁定不允许复制
			Integer lockStatus = budgetLockRecordService.getLockStatus(signPlanVersion.getProjectId(),"sign");
			if(lockStatus != null && lockStatus.intValue() == WhetherEnum.YES.getKey()) {
				throw new MsgException(CodeEnum.VERSION_IS_LOCK);
			}
			//2、分期已存在定稿版不允许复制
			boolean isExistFinalVersion = budgetLockRecordService.isExistFinalVersion(signPlanVersion.getProjectfId(),"sign",versionIdentify);
			if(isExistFinalVersion) {
				throw new MsgException(CodeEnum.SIGN_VERSION_EXIST_FINAL);
			}
			//3、分期的经营方式全部都是可租或不可租售的分期，不允许创建版本
			if (!getStageIsSaly(signPlanVersion.getSourceSupplyId())) {
		          throw new MsgException(CodeEnum.CREATE_NOT_BUILD_SALY_TYPE_ERROR);
	        }
			//4、分期禁用不允许复制
			MdmStage mdmStage = stageMapper.selectByFId(signPlanVersion.getProjectfId(), IsDeleteEnum.NO.getKey());
			if(mdmStage != null && StrUtils.isNotEmpty(mdmStage.getStatus()) && mdmStage.getStatus().equals(StageStatusEnum.INACTIVE.getKey())) {
				 throw new MsgException(CodeEnum.INACTIVE_STAGE_NOT_BUDGET);
			}
			//5、状态不是审批通过或系统生产不允许复制
			String state = signPlanVersion.getVersionState();
			if(state.equals(VersionStatusEnum.SUCCESSAPPROVED.getKey()) || state.equals(VersionStatusEnum.SYSGENERATION.getKey())) {
				//当前分期下无任何预算版，直接复制为定稿版
		        if(StrUtils.isEmpty(versionIdentify)) {
		        	List<ReturnPlanVersion> list = signPlanVersionMapper.selectListByStageIdAndVersionType(signPlanVersion.getProjectfId(),VersionTypeEunm.BUDGET.getKey(),IsDeleteEnum.NO.getKey());
		        	if(CollectionUtils.isEmpty(list)) {
		        		versionIdentify = LocalDateTime.now().getYear()+"年度预算定稿版";
		        	}else {
		        		throw new MsgException(CodeEnum.NOT_SET_BUDGET);
		        	}
		        }
				
				// 查询上一版签约计划
		        SignPlanVersion oldSignPlanVersion = signPlanVersionMapper.selectBudgetSignPlan(signPlanVersion.getProjectfId(), VersionTypeEunm.BUDGET.getKey(),
		        		versionIdentify, VersionStatusEnum.SYSGENERATION.getKey(), IsDeleteEnum.NO.getKey());
		        
		        SignPlanVersion newSignPlanVersion = new SignPlanVersion();
		        
		        BeanUtils.copyProperties(signPlanVersion, newSignPlanVersion);
		        // 新版本id
		        String signPlanVersionId = UUIDUtils.create();
		        newSignPlanVersion.setId(signPlanVersionId);
		        // 查询最新审批通过的签约版本
		        if (null == oldSignPlanVersion) {
		            newSignPlanVersion.setVersionNum(VersionUtils.bigVersionInc(null));
		        } else {
		            newSignPlanVersion.setVersionNum(VersionUtils.bigVersionInc(oldSignPlanVersion.getVersionNum()));
		        }
		        String affiliationMonth =signPlanVersion.getAffiliationMonth();
		        if(StrUtils.isEmpty(affiliationMonth)) {
		        	affiliationMonth = LocalDateTimeUtils.formatTime(signPlanVersion.getCreateTime(),"yyyy-MM");
		        }
		        newSignPlanVersion.setSourceSignId(versionId);
		        newSignPlanVersion.setVersionState(VersionStatusEnum.SUCCESSAPPROVED.getKey());
		        newSignPlanVersion.setVersionType(VersionTypeEunm.BUDGET.getKey());
		        newSignPlanVersion.setVersionCreate(VersionCreateEnum.MANUALCOPY.getKey());
		        newSignPlanVersion.setVersionIdentify(versionIdentify);
		        newSignPlanVersion.setCompileYear(versionIdentify.substring(0, 4));
		        newSignPlanVersion.setAffiliationMonth(affiliationMonth);
		        newSignPlanVersion.setCreateBy(user.getAlias());
		        newSignPlanVersion.setCreateTime(LocalDateTime.now());
		        newSignPlanVersion.setUpdateBy(null);
		        newSignPlanVersion.setUpdateTime(null);
		        newSignPlanVersion.setIsStageNewest(0);
		        //预算版签约版本
		        signPlanVersionMapper.insert(newSignPlanVersion);
		        //签约版本详情
		        signPlanVersionDetailMapper.copyVesionDetail(versionId,signPlanVersionId);
		        //签约供货版本详情
		        signPlanVersionSupplyDetailMapper.copyVesionDetail(versionId,signPlanVersionId);
		        //复制供货计划
		        copySupplyPlanVersion(newSignPlanVersion);
		        
		        saveVersionLog(signPlanVersionId,VersionEventEnum.SYS_GENERATE.getKey(),"",user.getAlias(),"新建签约计划",null);
		        
		        //修改基于的版本标签
		        signPlanVersion.setVersionIdentify(versionIdentify);
	        	signPlanVersionMapper.updateById(signPlanVersion);
	        	
	        	//推送Esb接口-费控系统
		        signPlanVersionDetailService.sendSignPlan(signPlanVersionId,2);
		        
			}else {
       		  throw new MsgException(CodeEnum.NOT_VALID_VERSION);
			}
		}
		
	}
	
	private boolean getStageIsSaly(String supplyPlanVersionId) {
		 List<String> salyTypeList = Arrays.asList(SalyTypeEnum.SALABLE.getKey(), SalyTypeEnum.STAGE_SELF_SUSTAINMENT.getKey());
		 int count = supplyPlanVersionDetailMapper.selectSupplyIsSalableOrStageSelfSustainment(supplyPlanVersionId,salyTypeList);
		 if(count > 0) {
			 return true;
		 }
		 return false;
	}
	
	 private void copySupplyPlanVersion(SignPlanVersion signPlanVersion) {
		String sourceSupplyId = signPlanVersion.getSourceSupplyId();
		SupplyPlanVersion sourceSupplyPlanVersion = supplyPlanVersionMapper.selectOneByVersionId(sourceSupplyId,IsDeleteEnum.NO.getKey());
		//查询上一版预算供货计划
		SupplyPlanVersion oldSupplyPlanVersion = supplyPlanVersionMapper.selectNewestBudgetVersion(signPlanVersion.getProjectfId(), 
				VersionTypeEunm.BUDGET.getKey(),signPlanVersion.getVersionIdentify(),IsDeleteEnum.NO.getKey());
		
		SupplyPlanVersion newSupplyPlanVersion = new SupplyPlanVersion();
	        
	    BeanUtils.copyProperties(sourceSupplyPlanVersion, newSupplyPlanVersion);
	    
        String supplyPlanVersionId = UUIDUtils.create();
        newSupplyPlanVersion.setId(supplyPlanVersionId);
        String versionNum = "";
        
        if (null == oldSupplyPlanVersion) {
        	versionNum = VersionUtils.bigVersionInc(null);
        } else {
        	versionNum = VersionUtils.bigVersionInc(oldSupplyPlanVersion.getVersionNum());
        }
        String affiliationMonth =sourceSupplyPlanVersion.getAffiliationMonth();
        if(StrUtils.isEmpty(affiliationMonth)) {
        	affiliationMonth = LocalDateTimeUtils.formatTime(sourceSupplyPlanVersion.getCreateTime(),"yyyy-MM");
        }
        
        newSupplyPlanVersion.setVersionNum(versionNum);
        newSupplyPlanVersion.setSourceSupplyId(sourceSupplyPlanVersion.getId());
        newSupplyPlanVersion.setVersionState(VersionStatusEnum.SYSGENERATION.getKey());
        newSupplyPlanVersion.setVersionType(VersionTypeEunm.BUDGET.getKey());
        newSupplyPlanVersion.setVersionName(VersionTypeEunm.BUDGET.getValue());
        newSupplyPlanVersion.setVersionIdentify(signPlanVersion.getVersionIdentify());
        newSupplyPlanVersion.setBudgetYear(signPlanVersion.getCompileYear());
        newSupplyPlanVersion.setVersionAttr(sourceSupplyPlanVersion.getVersionType().equals(VersionTypeEunm.INVESTMENT.getKey()) ? VersionAttrEnum.BEFORE_WARPLAN.getKey() : VersionAttrEnum.AFTER_WARPLAN.getKey() );
        newSupplyPlanVersion.setIsFinalize(0);
        newSupplyPlanVersion.setIsAssessmentVersion(0);
        newSupplyPlanVersion.setConfirmStatus(0);
        newSupplyPlanVersion.setAffiliationMonth(affiliationMonth);
        newSupplyPlanVersion.setCreateBy(Constants.SYS);
        newSupplyPlanVersion.setCreateTime(LocalDateTime.now());
        newSupplyPlanVersion.setUpdateBy(Constants.SYS);
        newSupplyPlanVersion.setUpdateTime(LocalDateTime.now());
        
        supplyPlanVersionMapper.insert(newSupplyPlanVersion);
        
        supplyPlanVersionDetailMapper.copySupplyPlanVersionDeatil(sourceSupplyPlanVersion.getId(),supplyPlanVersionId);
        
        String versionName = signPlanVersion.getVersionIdentify() +versionNum+"-"+LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMdd");
        versionLogService.saveVersionLogInfo(sourceSupplyPlanVersion.getProjectId(),sourceSupplyPlanVersion.getProjectfId(),ModuleTypeEunm.SUPPLY_PLAN.getKey(),
        		VersionEventEnum.SYS_GENERATE.getKey(),supplyPlanVersionId,versionName,
        		VersionStatusEnum.SYSGENERATION.getKey(),VersionStatusEnum.SYSGENERATION.getKey(),ModifySourceTypeEunm.FOUR.getKey(),
        		sourceSupplyPlanVersion.getSourcePriceId(),Constants.SYS,LocalDateTime.now(),"自动复制预算版供货计划版本","复制预算版供货计划版本",IsDeleteEnum.NO.getKey(),Constants.SYS,LocalDateTime.now());

        
	}
	 

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void copyBudgetVersion(String versionId,String versionIdentify, IdmUser user) {
		SignPlanVersion signPlanVersion = signPlanVersionMapper.selectByIdAndDel(versionId, IsDeleteEnum.NO.getKey());
		if(signPlanVersion != null) {
			//1、非预算季不允许复制
	  		if(StrUtils.isEmpty(versionIdentify)) {
	  			throw new MsgException(CodeEnum.NOT_BUDGET);
	  		}
			//2、项目锁定不允许复制
        	Integer lockStatus = budgetLockRecordService.getLockStatus(signPlanVersion.getProjectId(),"sign");
			if(lockStatus != null && lockStatus.intValue() == WhetherEnum.YES.getKey()) {
				throw new MsgException(CodeEnum.VERSION_IS_LOCK);
			}
			//3、分期已存在定稿版不允许复制
			boolean isExistFinalVersion = budgetLockRecordService.isExistFinalVersion(signPlanVersion.getProjectfId(),"sign",versionIdentify);
			if(isExistFinalVersion) {
				throw new MsgException(CodeEnum.SIGN_VERSION_EXIST_FINAL_NOT);
			}
			//4、分期的经营方式全部都是可租或不可租售的分期，不允许创建版本
			if (!getStageIsSaly(signPlanVersion.getSourceSupplyId())) {
		          throw new MsgException(CodeEnum.CREATE_NOT_BUILD_SALY_TYPE_ERROR);
	        }
			//5、分期禁用不允许复制
			MdmStage mdmStage = stageMapper.selectByFId(signPlanVersion.getProjectfId(), IsDeleteEnum.NO.getKey());
			if(mdmStage != null && StrUtils.isNotEmpty(mdmStage.getStatus()) && mdmStage.getStatus().equals(StageStatusEnum.INACTIVE.getKey())) {
				 throw new MsgException(CodeEnum.INACTIVE_STAGE_NOT_COPY_BUDGET);
			}
			
			SignPlanVersion newSignPlanVersion = new SignPlanVersion();
			
			BeanUtils.copyProperties(signPlanVersion, newSignPlanVersion);
			
			String affiliationMonth =signPlanVersion.getAffiliationMonth();
	        if(StrUtils.isEmpty(affiliationMonth)) {
	        	affiliationMonth = LocalDateTimeUtils.formatTime(signPlanVersion.getCreateTime(),"yyyy-MM");
	        }
			
	        String versionNum = getVersionNum(signPlanVersion.getProjectfId(),signPlanVersion.getVersionType());
	        String signPlanVersionId = UUIDUtils.create();
	        
	        newSignPlanVersion.setId(signPlanVersionId);
	        newSignPlanVersion.setVersionNum(versionNum);
	        newSignPlanVersion.setSourceSignId(versionId);
	        newSignPlanVersion.setVersionIdentify(versionIdentify);
	        newSignPlanVersion.setCompileYear(versionIdentify.substring(0, 4));
	        newSignPlanVersion.setVersionState(VersionStatusEnum.SUCCESSAPPROVED.getKey());
	        newSignPlanVersion.setVersionCreate(VersionCreateEnum.MANUALCOPY.getKey());
	        newSignPlanVersion.setAffiliationMonth(affiliationMonth);
	        newSignPlanVersion.setCreateBy(user.getAlias());
	        newSignPlanVersion.setCreateTime(LocalDateTime.now());
	        newSignPlanVersion.setUpdateBy(null);
	        newSignPlanVersion.setUpdateTime(null);
	        newSignPlanVersion.setIsStageNewest(0);
	        //预算版签约版本
	        signPlanVersionMapper.insert(newSignPlanVersion);
	        //签约版本详情
	        signPlanVersionDetailMapper.copyVesionDetail(versionId,signPlanVersionId);
	        //签约供货版本详情
	        signPlanVersionSupplyDetailMapper.copyVesionDetail(versionId,signPlanVersionId);
	        //复制供货计划
	        copySupplyPlanVersion(newSignPlanVersion);
	        
	        //修改基于签约计划版本标签
	        SignPlanVersion sourceSignPlanVersion = signPlanVersionMapper.selectByIdAndDel(signPlanVersion.getSourceSignId(), IsDeleteEnum.NO.getKey());
	        sourceSignPlanVersion.setVersionIdentify(versionIdentify);
        	signPlanVersionMapper.updateById(sourceSignPlanVersion);
	        
	        saveVersionLog(signPlanVersionId,VersionEventEnum.SYS_GENERATE.getKey(),"",user.getAlias(),"新建签约计划",null);
		
	        //推送Esb接口-费控系统
	        signPlanVersionDetailService.sendSignPlan(signPlanVersionId,2);
		}
		
	}
	
	/**
     * 获取版本号
     * @param projectfId 分期id
     * @param versionType 版本类型
     * @return
     */
    private String getVersionNum(String projectfId, String versionType) {
        String versionNum = null;
        List<String> versionTypes = Arrays.asList(versionType);
        List<String> versionStatuss = Arrays.asList(VersionStatusEnum.SUCCESSAPPROVED.getKey(),VersionStatusEnum.SYSGENERATION.getKey());
        // 查询最新审批通过的签约版本
        SignPlanVersion oldSignPlanVersion = signPlanVersionMapper.selectNewesVersion(projectfId, versionTypes, versionStatuss, IsDeleteEnum.NO.getKey());
        //版本号赋值处理
        if (null != oldSignPlanVersion) {
            if (VersionTypeEunm.DYNAMIC.getKey().equals(versionType)) {
                if (oldSignPlanVersion.getAffiliationMonth().equals(LocalDateTimeUtils.getLocalMonth(LocalDateTime.now()))) {
                    versionNum = oldSignPlanVersion.getVersionNum();
                }
            }else {
                versionNum = oldSignPlanVersion.getVersionNum();
            }
        }
        return VersionUtils.bigVersionInc(versionNum);
    }
	

	public boolean isAfterWarplan(String projectFId) {
	        List<String> priceVersionTypes = new ArrayList<>();
	        priceVersionTypes.add(VersionTypeEunm.WARPLAN.getKey());
	        priceVersionTypes.add(VersionTypeEunm.GETPRICE.getKey());
	        priceVersionTypes.add(VersionTypeEunm.DYNAMIC.getKey());
	        List<PriceVersion> supplyPlanVersionList = signPlanVersionMapper.selectPriceByVersionTypes(projectFId,
	                priceVersionTypes, IsDeleteEnum.NO.getKey());
	        if ( CollectionUtils.isNotEmpty(supplyPlanVersionList)) {
	            return true;
	        }
	        return false;
	 }
	 
	 	/**
	     * 版本日志
	     * @param versionId 版本id
	     * @param event 版本事件
	     * @param beforeState 变更前的状态
	     * @param alias 创建人
	     * @param title 事件标题
	     * @param content 事件内容
	     */
	    public void saveVersionLog(String versionId, String event, String beforeState, String alias, String title, String content){
	        SignPlanVersion signPlanVersion = signPlanVersionMapper.selectById(versionId);
	        String versionName = VersionUtils.getFullName(signPlanVersion);
	        VersionLog versionLog = new VersionLog();
	        versionLog.setId(UUIDUtils.create());
	        versionLog.setProjectId(signPlanVersion.getProjectId());
	        versionLog.setProjectfId(signPlanVersion.getProjectfId());
	        versionLog.setModuleType(ModuleTypeEunm.SIGN_PLAN.getKey());
	        versionLog.setEvent(event);
	        versionLog.setVersionId(versionId);
	        versionLog.setVersionName(versionName);
	        versionLog.setBeforeState(beforeState);
	        versionLog.setAfterState(signPlanVersion.getVersionState());
	        versionLog.setModifySourceType(null);
	        versionLog.setModifySourceId(null);
	        versionLog.setOperationBy(alias);
	        versionLog.setOperationTime(LocalDateTime.now());
	        versionLog.setTitle(title);
	        versionLog.setContent(content);
	        versionLog.setIsDelete(0);
	        versionLog.setCreateBy(alias);
	        versionLog.setCreateTime(LocalDateTime.now());
	        versionLogMapper.insert(versionLog);
	    }

		@Override
		public void sendInformFetch(String projectId,int type) {
			EsbInformReqParam param = EsbInformReqParam(projectId);
			BasicAuthClient bac = new BasicAuthClient();
			String result =  bac.post(informFetchUrl, JSON.toJSONString(param),api_name,api_key);
			log.info("##### 下发通知下游系统取数接口 参数："+ JSON.toJSONString(param));
			log.info("##### 下发通知下游系统取数接口 响应数据："+ result);
			if(StrUtils.isNotEmpty(result)) {
				JSONObject object = (JSONObject) JSONObject.parse(result);
				JSONObject esbInfoObj = object.getJSONObject("esbInfo");
				String returnStatus = esbInfoObj.getString("returnStatus");
				//成功
				if(returnStatus.equals("S")) {
					EsbPushLog log = esbPushLogService.getByProjectId(projectId);
					if(log == null) {
						log = new EsbPushLog();
						log.setId(UUIDUtils.create());
						log.setProjectId(projectId);
						log.setUrl(informFetchUrl);
						log.setSys("预算系统");
						log.setPushContent(JSON.toJSONString(param));
						log.setReturnContent(result);
						log.setCreateTime(LocalDateTime.now());
						log.setIsSuccess(IsDeleteEnum.NO.getKey());
						log.setFailTime(IsDeleteEnum.NO.getKey());
						log.setType(type);
						esbPushLogService.insert(log);
					}else {
						if(log.getIsSuccess().intValue() == IsDeleteEnum.NO.getKey()) {
							log.setCreateTime(LocalDateTime.now());
						}else {
							log.setCreateTime(LocalDateTime.now());
							log.setIsSuccess(IsDeleteEnum.NO.getKey());
						}
						log.setType(type);
						esbPushLogService.update(log);
					}
				}else {
					EsbPushLog log = esbPushLogService.getByProjectId(projectId);
					if(log == null) {
						log = new EsbPushLog();
						log.setId(UUIDUtils.create());
						log.setProjectId(projectId);
						log.setUrl(informFetchUrl);
						log.setSys("预算系统");
						log.setPushContent(JSON.toJSONString(param));
						log.setReturnContent(result);
						log.setCreateTime(LocalDateTime.now());
						log.setIsSuccess(IsDeleteEnum.NO.getKey());
						log.setFailTime(IsDeleteEnum.YES.getKey());
						log.setType(type);
						esbPushLogService.insert(log);
					}else {
						if(log.getIsSuccess().intValue() == IsDeleteEnum.NO.getKey()) {
							log.setCreateTime(LocalDateTime.now());
						}else {
							log.setCreateTime(LocalDateTime.now());
							log.setFailTime(log.getFailTime().intValue() + 1);
						}
						log.setType(type);
						esbPushLogService.update(log);
					}
				}
			}
		}

		private EsbInformReqParam EsbInformReqParam(String projectId) {
			EsbInformReqParam param = new EsbInformReqParam();
			PublicInformFetchBO bo = new PublicInformFetchBO();
			MdmProject project = projectMapper.selectByProjectId(projectId, IsDeleteEnum.NO.getKey());
			BudgetVersionIdentify obj = budgetVersionIdentifyMapper.selectVersion(IsDeleteEnum.NO.getKey());
			if(project != null) {
				bo.setProjectId(projectId);
				bo.setProjectName(project.getProjectName());
				bo.setSysCode(Constants.SYS_CODE);
			}
			if(obj != null ) {
				bo.setVersionCode(obj.getVersionCode());
				bo.setVersionName(obj.getVersionIdentify());
			}
			EsbInfoReq esbInfo = new EsbInfoReq();
			esbInfo.setAttr1("null");
			esbInfo.setAttr2("null");
			esbInfo.setAttr3("null");
			esbInfo.setInstId("");
			esbInfo.setRequestTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
			param.setEsbInfo(esbInfo);
			param.setRequestInfo(bo);
			return param;
		}

	    
	
}
